package com.voto.sunflower.activity.me;

import retrofit.RetrofitError;
import retrofit.client.Response;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;

import com.voto.sunflower.R;
import com.voto.sunflower.activity.BaseActivity;
import com.voto.sunflower.activity.me.UpdateVersionCallback.UpdateVersionListener;
import com.voto.sunflower.model.response.UpdateVersionResponse;
import com.voto.sunflower.retrofit.ClientHttpService;
import com.voto.sunflower.retrofit.RestError;

public class UpdateActivity extends BaseActivity implements Updater.UpdateCallback {

	boolean isDownLoad = false;
	private TextView mTvInfo;
	protected String TAG = "UpdateActivity";
	private UpdateVersionCallback updateVersion;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// getWindow().requestFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_update);

		// mTvInfo = (TextView) findViewById(R.id.tv_info);
		// mTvInfo.setText(R.string.update_checking);

		setCallback();
		showBlankWaitDialog();
		ClientHttpService.getOtherService().checkVersion(getVersionCode(), updateVersion);
	}

	private void setCallback() {
		updateVersion = new UpdateVersionCallback();
		updateVersion.setUpdateListener(new UpdateVersionListener() {

			@Override
			public void success(UpdateVersionResponse updateVersionResponse, Response response) {
				dismissDialog();
				String newVersion = updateVersionResponse.getVersion();
				compareVersions(newVersion);
			}

			@Override
			public void failure(RetrofitError error) {
				dismissDialog();
				if (error.getResponse() != null) {
					int statusCode = error.getResponse().getStatus();
					if (statusCode == 500 || statusCode == 501) {
						final RestError body = (RestError) error.getBodyAs(RestError.class);
						showNetworkErrorDialog(body.errorDetails, null);
					} else if (statusCode == 408) {
						showNetworkErrorDialog(getString(R.string.connect_overtime), null);
					} else {
						showNetworkErrorDialog(error.getMessage(), null);
					}
				}
				Intent mIntent = new Intent();
				mIntent.setClass(UpdateActivity.this, SettingActivity.class);
				mIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(mIntent);
				finish();
			}

		});

	}

	protected void compareVersions(String newVersion) {
		try {
			if (null != newVersion) {
				Log.i(TAG, "info " + newVersion);
				String nowVersion = getVersionName();
				if (newVersion.matches("^[0-9]*$")) {
					nowVersion = getVersionCode();
				}
				// check if need success
				if (newVersion.compareTo(nowVersion) > 0) {
					// need update
					// showUpdataDialog(newVersion,
					// URLHelper.getAbsoluteUrl(newVersion.url));
					mTvInfo.setText("");
					return;
				} else {
					finish();
				}
			} else {
				finish();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private String getVersionName() throws Exception {
		PackageManager packageManager = getPackageManager();
		PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(), 0);
		return packInfo.versionName;
	}

	private String getVersionCode() {
		// 获取发送来的当前版本
		Bundle budle = new Bundle();
		budle = this.getIntent().getExtras();
		return budle.getString("version", "");
	}

	protected void showUpdataDialog(final String version, final String url) {
		new AlertDialog.Builder(UpdateActivity.this).setTitle(R.string.update_sure_update)
				.setMessage(R.string.update_new_version)
				.setNegativeButton(R.string.update_next, new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						Intent mIntent = new Intent();
						mIntent.setClass(UpdateActivity.this, SettingActivity.class);
						mIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						startActivity(mIntent);
						finish();
					}
				}).setPositiveButton(R.string.update_immediately, new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						doUpdate(version, url);
					}
				}).show();
	}

	private void doUpdate(String version, String url) {
		Updater.update(UpdateActivity.this, this, version, url);
	}

	// protected void installApk() {
	// Intent intent = new Intent();
	// // 执行动作
	// intent.setAction(Intent.ACTION_VIEW);
	// // 执行的数据类型
	// intent.setDataAndType(Uri.fromFile(new
	// File(Environment.getExternalStorageDirectory() + "/Sexy.apk")),
	// "application/vnd.android.package-archive");
	// startActivity(intent);
	// }

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && isDownLoad) // 监控/拦截/屏蔽返回键
		{
			showCancelDialog();
			return true;
		}

		return super.onKeyDown(keyCode, event);
	}

	private void showCancelDialog() {

		new AlertDialog.Builder(UpdateActivity.this).setTitle(R.string.update_sure_exit).setMessage(R.string.update_give_up)
				.setPositiveButton(R.string.update_exit, new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						isDownLoad = false;
						finish();
					}
				}).setNegativeButton(R.string.update_continue, null).show();

	}

	@Override
	public void onUpdateFail(String reason) {
		Toast.makeText(getApplicationContext(), R.string.update_fail, Toast.LENGTH_SHORT).show();
		Intent mIntent = new Intent();
		mIntent.setClass(UpdateActivity.this, SettingActivity.class);
		mIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(mIntent);
		finish();
	}

	@Override
	public void onUpdatePercent(int percent) {
		mTvInfo.setText(getString(R.string.update_download, percent));
	}

	@Override
	public void onUpdateReady() {
		finish();
	}
}
